<template>
  <el-dialog
    v-model="dialogFormVisible"
    title="字典"
    width="1100px"
    @close="close"
  >
    <div class="dynamic-table-container">
      <el-form ref="formRef" :key="index" :model="form">
        <el-form-item :label-width="0">
          <div class="vab-form-table">
            <vab-query-form>
              <vab-query-form-top-panel :span="12">
                <el-button
                  :icon="Plus"
                  type="primary"
                  @click="handleAdd($event)"
                >
                  添加
                </el-button>
              </vab-query-form-top-panel>
            </vab-query-form>
            <el-table :key="toggleIndex" border :data="form.dictList">
              <el-table-column
                v-if="drag"
                align="center"
                label="操作"
                width="120"
              >
                <template #default>
                  <vab-icon
                    class="vab-rank"
                    icon="drag-move-2-line"
                    style="cursor: move"
                  />
                </template>
              </el-table-column>
              <slot></slot>
              <el-table-column
                align="center"
                label="字典名称"
                width="200"
                prop="name"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.name"
                    :disabled="row.exploit === '1' ? true : false"
                  />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="字典颜色"
                width="200"
                prop="dictColor"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.dictColor"
                    :disabled="row.exploit === '1' ? true : false"
                    type="color"
                  />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="排序"
                width="200"
                prop="sort"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.sort"
                    :disabled="row.exploit === '1' ? true : false"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="300">
                <template #default="{ $index, row }">
                  <el-button
                    :icon="Delete"
                    plain
                    type="danger"
                    style="margin-right: 20px"
                    :disabled="row.exploit === '1' ? true : false"
                    @click="handleDelete(row, $index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    :icon="Delete"
                    plain
                    type="success"
                    :disabled="row.exploit === '1' ? true : false"
                    @click="handleConfirm(row, $index)"
                  >
                    保存
                  </el-button>
                </template>
              </el-table-column>
              <template #empty>
                <el-empty class="vab-data-empty" description="暂无数据" />
              </template>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
  import { Delete, Plus, Search } from '@element-plus/icons-vue'
  import { addDict, deleteDict, editDict } from '@/api/dictionaryManagement'

  export default defineComponent({
    name: 'DictionaryComponent',
    props: {
      dictListData: {
        type: Array,
        default: () => {
          return []
        },
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        formRef: null,
        toggleIndex: 0,
        rowTemplate: {},
        drag: true,
        form: {
          dictList: [],
        },
        dialogFormVisible: false,
      })

      watch(
        props.dictListData,
        (newValue, oldValue) => {
          console.log(`新的值是：${newValue}，旧的值是：${oldValue}`)
          if (newValue !== oldValue) {
            state.form.dictList = props.dictListData
          }
        },
        {
          deep: true,
        }
      )

      const showEdit = (row) => {
        state.dialogFormVisible = true
        if (row) {
          state.form.dictList = JSON.parse(JSON.stringify(row))
        }
      }
      const handleAdd = () => {
        state.form.dictList.push({})
      }
      const handleDelete = async (row, index) => {
        if (row.id) {
          try {
            const { msg } = await deleteDict({ ids: row.id })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          } catch (e) {
            console.error(e)
          }
        }
        state.form.dictList.splice(index, 1)
      }
      const handleConfirm = async (row) => {
        if (!row.name || !row.value) {
          $baseMessage('请输入完整信息', 'error', 'vab-hey-message-error')
          return
        }
        if (row.id) {
          try {
            const { msg } = await editDict(row)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          } catch (e) {
            console.error(e)
          }
        } else {
          row.typeCode = 'assetCheckType'
          try {
            const { msg } = await addDict(row)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          } catch (e) {
            console.error(e)
          }
        }
      }

      /**
       * resetFields()已重置form,不需要再去操作form
       **/
      const close = () => {
        state.dialogFormVisible = false
      }

      onMounted(() => {
        state.tableData &&
          state.tableData.forEach((item) => {
            state.newIndexList.push(item.id)
          })
      })
      return {
        ...toRefs(state),
        showEdit,
        handleAdd,
        handleDelete,
        handleConfirm,
        Delete,
        Plus,
        Search,
        close,
      }
    },
  })
</script>

<style scoped>
  .tree-container {
    width: 100%;
    min-height: 200px;
    border: 1px solid #dcdfe6;
  }
</style>
